<template>
    <div class="snow-page">
        <a-card title="触发器添加" style="width: 99%" hoverable>
            <template #extra>
                <a-button size="mini" type="primary" @click="goBack">返回</a-button>
            </template>
            <div class="">
                <div class="snow-inner-page">
                    <a-row :gutter="16">
                        <a-form ref="formRef" :size="form.size" :model="form" auto-label-width @submit="handleSubmit">
                            <div style="display: flex">
                                <a-col :span="12">

                                    <a-form-item field="name" label="触发器名称"
                                        :rules="[{ required: true, message: '触发器名称不能为空' }]">
                                        <a-input v-model="form.name" placeholder="触发器名称" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="node_id" label="网关"
                                        :rules="[{ required: true, message: '网关不能为空' }]">
                                        <a-select v-model="form.node_id" placeholder="选择网关" allow-clear
                                            @change="nodeChange">
                                            <a-option v-for="(item, index) in sbList" :key="index" :value="item.id">{{
                                                item.name
                                                }}</a-option>
                                        </a-select>
                                    </a-form-item>

                                    <a-form-item field="from_sensor_id" label="传感器"
                                        :rules="[{ required: true, message: '传感器不能为空' }]">
                                        <a-select v-model="form.from_sensor_id" placeholder="传感器" allow-clear>
                                            <a-option v-for="(item, index) in cgqList" :key="index" :value="item.id">{{
                                                item.name
                                                }}</a-option>
                                        </a-select>
                                    </a-form-item>

                                    <a-form-item field="iot_trigger_condition_type" label="触发类型"
                                        :rules="[{ required: true, message: '触发类型不能为空' }]">
                                        <a-select v-model="form.iot_trigger_condition_type" placeholder="触发类型"
                                            allow-clear>
                                            <a-option v-for=" (item, index) in options28" :key="index"
                                                :value="item.id">{{
                                                    item.name }}</a-option>
                                        </a-select>
                                    </a-form-item>


                                    <a-form-item field="x_value" label="X" v-if="form.iot_trigger_condition_type == 29 ||
                                        form.iot_trigger_condition_type == 31 || form.iot_trigger_condition_type == 32 ||
                                        form.iot_trigger_condition_type == 33 || form.iot_trigger_condition_type == 34 ||
                                        form.iot_trigger_condition_type == 189
                                    ">
                                        <a-input v-model="form.x_value" placeholder="X" allow-clear />
                                    </a-form-item>

                                    <a-form-item field="y_value" label="Y"
                                        v-if="form.iot_trigger_condition_type == 30 ||
                                            form.iot_trigger_condition_type == 31 || form.iot_trigger_condition_type == 189">
                                        <a-input v-model="form.y_value" placeholder="Y" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="m_value" label="M"
                                        v-if="form.iot_trigger_condition_type == 280
                                            || form.iot_trigger_condition_type == 33 || form.iot_trigger_condition_type == 34">
                                        <a-input v-model="form.m_value" placeholder="M" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="iot_trigger_action_type" label="动作类型">
                                        <a-select v-model="form.iot_trigger_action_type" placeholder="动作类型" allow-clear
                                            multiple>
                                            <a-option v-for="(item, index) in options49" :key="index"
                                                :value="item.id">{{
                                                    item.name
                                                }}</a-option>
                                        </a-select>
                                    </a-form-item>
                                    <a-form-item field="contactor" label="联系人信息">
                                        <a-select v-model="form.contactor" placeholder="联系人信息" allow-clear multiple>
                                            <a-option v-for="(item, index) in userList" :key="index" :value="item.id">{{
                                                item.name
                                                }}</a-option>
                                        </a-select>
                                    </a-form-item>

                                </a-col>
                                <a-col :span="12">
                                    <a-form-item field="iot_trigger_alarm_flag" label="生成报警信息"
                                        :rules="[{ required: true, message: '生成报警信息不能为空' }]">
                                        <a-select v-model="form.iot_trigger_alarm_flag" placeholder="生成报警信息"
                                            allow-clear>
                                            <a-option value="36">开启</a-option>
                                            <a-option value="37">关闭</a-option>
                                        </a-select>
                                    </a-form-item>


                                    <a-form-item field="trigger_inteval_time" label="循环触发间隔[秒]"
                                        :rules="[{ required: true, message: '循环触发间隔[秒]不能为空' }]">
                                        <a-input v-model="form.trigger_inteval_time" placeholder="循环触发间隔[秒]"
                                            allow-clear />
                                    </a-form-item>

                                    <a-form-item field="iot_trigger_status" label="是否开启">
                                        <a-select v-model="form.iot_trigger_status" placeholder="是否开启" allow-clear>
                                            <a-option value="43">开启</a-option>
                                            <a-option value="44">暂停</a-option>
                                        </a-select>
                                    </a-form-item>
                                    <a-form-item v-if="form.iot_trigger_alarm_flag == 36"
                                        field="iot_trigger_alarm_level" label="报警级别">
                                        <a-select v-model="form.iot_trigger_alarm_level" placeholder="报警级别" allow-clear>
                                            <a-option value="39">严重</a-option>
                                            <a-option value="40">紧急</a-option>
                                            <a-option value="41">一般</a-option>
                                        </a-select>
                                    </a-form-item>
                                    <a-form-item field="recovery" label="报警恢复触发">
                                        <a-select v-model="form.recovery" placeholder="报警恢复触发" allow-clear>
                                            <a-option value="36">开启</a-option>
                                            <a-option value="37">关闭</a-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </div>
                            <div style="text-align: center; margin-left: 35%">
                                <a-form-item>
                                    <a-space>
                                        <a-button type="primary" html-type="submit">提交</a-button>
                                        <a-button @click="onReset">重置</a-button>
                                    </a-space>
                                </a-form-item>
                            </div>
                        </a-form>
                    </a-row>
                </div>
            </div>

            <a-modal v-model:visible="mapopen" title="选择位置" width="50%">
                <div id="mapContainer" style="width: 100%; height: 400px"></div>
                <div class="input-container">
                    <input v-model="longitude" @keyup.enter="locatePosition" placeholder="输入经度"
                        class="coordinate-input" />
                    <input v-model="latitude" @keyup.enter="locatePosition" placeholder="输入纬度"
                        class="coordinate-input" />
                    <button @click="locatePosition" class="locate-button">定位</button>
                </div>
            </a-modal>
        </a-card>
    </div>
</template>


<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { ref, reactive, onMounted } from "vue";
// import {regionData} from "element-china-area-data";
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { getProjectAPI } from "@/api/modules/project/index";
import { addtriggerAPI, updatetriggerAPI } from "@/api/modules/trigger/index";
import { getDictBycodeAPI } from "@/api/modules/dictionary/index";
//
import { getConcactAPI } from "@/api/modules/concact/index";
import { getsensorListAPI } from "@/api/modules/sensor/index"

// import axios from "axios";
const router = useRouter();
onMounted(() => {
    getDictBycodeAPIfun();
    getDictBycodeAPIfun2();
    getConcactAPIway();
    init602();
    getProinit();
    getInit();
    getFuzhi();
});

const optinos602 = ref([]);

async function init602() {
    let res = await getDictBycodeAPI(602);
    if (res.status == 2) {
        optinos602.value = res.data
    }
}

const sbList = ref([])

async function getProinit() {
    let form = {
        name: "",
        scene_id: "",
        scene_ids: [],

    };
    let obj = {
        paged: 1,
        pageSize: 500
    }
    let res = await getProjectAPI(obj, form);

    sbList.value = [];
    if (res.status == 2) {

        sbList.value = res.data.data;
    }
}


const userList = ref([])

async function getConcactAPIway() {
    let form = {
        name: "",
        phone: "",
        user_id: "1"
    };
    let obj = {
        paged: 1,
        pageSize: 500
    }
    let res = await getConcactAPI(obj, form);

    userList.value = [];
    if (res.status == 2) {

        userList.value = res.data.data;
    }
}

const cgqList = ref([])

async function nodeChange(e) {
    let resobj = sbList.value.filter((val) => {
        return val.id == e
    })
    form.equip_code = resobj[0].cq_equip_code


    let obj = {
        paged: 1,
        pageSize: 500
    }
    let obj2 = { node_id: e.value, data_type: -1, sensor_device_id: "" }

    cgqList.value = [];
    let res = await getsensorListAPI(obj, obj2) as any;
    if (res.status == 2) {
        cgqList.value = res.data.data
    }
}





const options28 = ref([]);
async function getDictBycodeAPIfun() {
    // let obj={}
    let res = await getDictBycodeAPI(28);
    if (res.status == 2) {
        options28.value = res.data;
    }
}
const options49 = ref([]);
async function getDictBycodeAPIfun2() {
    let res = await getDictBycodeAPI(49);
    if (res.status == 2) {
        options49.value = res.data;
    }
}




async function getFuzhi() {
    let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
    if (userInfo.sharedObject.id) {

        form.node_id = userInfo.sharedObject.node_id;
        let obj = {
            paged: 1,
            pageSize: 500
        }
        let obj2 = { node_id: userInfo.sharedObject.node_id, data_type: -1, sensor_device_id: "" }

        cgqList.value = [];
        let res = await getsensorListAPI(obj, obj2) as any;
        if (res.status == 2) {
            cgqList.value = res.data.data
            form.from_sensor_id = userInfo.sharedObject.from_sensor_id;
        }
        form.name = userInfo.sharedObject.name;
        form.iot_trigger_condition_type = userInfo.sharedObject.iot_trigger_condition_type;
        form.x_value = userInfo.sharedObject.x_value;
        form.y_value = userInfo.sharedObject.y_value;
        form.m_value = userInfo.sharedObject.m_value;

        //动作类型
        if (userInfo.sharedObject.iot_trigger_action_type) {
            let arr2 = userInfo.sharedObject.iot_trigger_action_type.split(",").map(function (item) {
                return parseInt(item, 10); // 使用parseInt将字符串转换为数字
            });
            form.iot_trigger_action_type = arr2
        }


        //联系人
        let action_params = JSON.parse(userInfo.sharedObject.action_params)
        if (action_params.contactor) {
            // 使用split方法分割字符串，然后使用map转换每个子字符串为数字
            let numArray = action_params.contactor.split(",").map(function (item) {
                return parseInt(item, 10); // 使用parseInt将字符串转换为数字
            });
            form.contactor = numArray
        }

        if (userInfo.sharedObject.iot_trigger_alarm_flag) {
            form.iot_trigger_alarm_flag = (userInfo.sharedObject.iot_trigger_alarm_flag + '')
        }

        form.trigger_inteval_time = userInfo.sharedObject.trigger_inteval_time
        form.iot_trigger_status = userInfo.sharedObject.iot_trigger_status + ''
        form.iot_trigger_alarm_level = userInfo.sharedObject.iot_trigger_alarm_level + ''
        form.recovery = userInfo.sharedObject.recovery + ''
        form.id = userInfo.sharedObject.id


    }

}

const mapopen = ref(false);

const treeNodes = ref([]);
const treeAllNodes = ref([]);
async function getInit() {
    let obj = {};
    let res = await getAllqiyeAPI(obj);
    if (res.status == 2) {
        treeNodes.value = generateTreeNodes(res.data);
        treeAllNodes.value = res.data
    }
}



function generateTreeNodes(data) {
    const nodeMap = new Map();
    const rootNodes = [];

    // First pass: create nodes and store them in a map
    data.forEach(item => {
        const node = {
            id: item.id,
            name: item.name,
            children: [],
            data: item // Store all original data
        };
        nodeMap.set(item.cq_company_code, node);
    });

    // Second pass: build the tree structure
    data.forEach(item => {
        const node = nodeMap.get(item.cq_company_code);
        if (item.cq_parent_code === "0") {
            rootNodes.push(node);
        } else {
            const parentNode = nodeMap.get(item.cq_parent_code);
            if (parentNode) {
                parentNode.children.push(node);
            } else {
                console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
                rootNodes.push(node); // Add to root if parent not found
            }
        }
    });

    return rootNodes;
}

const handleSubmit = async ({ values, errors }) => {

    if (errors) {
        return;
    }
    console.log(values);
    let action_params = {
        control_device: "",
        control_device_status: "36",
        contactor: values.contactor.join(",")
    }
    values.action_params = JSON.stringify(action_params)
    delete values.contactor;
    values.condition_params = []
    if (values.x_value) {
        values.condition_params.push(values.x_value)

    }
    if (values.y_value) {
        values.condition_params.push(values.y_value)

    }
    if (values.m_value) {
        values.condition_params.push(values.m_value)
        delete values.m_value
    }
    values.condition_params = values.condition_params.join(",")

    values.iot_trigger_action_type = values.iot_trigger_action_type.join(",")


    let res: any = "";
    if (form.id) {
        res = (await updatetriggerAPI(values)) as any;
    } else {
        res = (await addtriggerAPI(values)) as any;
    }

    if (res.status == 2) {
        Message.success("操作成功");
        // router.back();
        setTimeout(function () {
            router.back();
        }, 600)
    } else {
        Message.error(res.statusMsg);
    }
};

// 将序列化的字符串美观输出，\t 换行

const form = reactive({}) as any;

const formRef = ref();
const onReset = () => {
    formRef.value.resetFields();
};

function goBack() {
    router.back();
}

function onSearch() {
    mapopen.value = true;

    setTimeout(function () {
        initMap();
    }, 500);
}
const longitude = ref("");
const latitude = ref("");
const map = ref({}) as any;
let marker: any;
const locatePosition = () => {
    const lon = parseFloat(longitude.value);
    const lat = parseFloat(latitude.value);

    form.lonLat = lon + "," + lat;
    if (isNaN(lon) || isNaN(lat)) {
        alert("请输入有效的经纬度");
        return;
    }

    const lnglat = new window.T.LngLat(lon, lat);

    // 移动地图中心
    map.value.panTo(lnglat);

    // 清除现有标记
    map.value.clearOverLays();

    // 添加新标记
    marker = new window.T.Marker(lnglat);
    map.value.addOverLay(marker);

    // 设置缩放级别
    map.value.setZoom(13);
};
function initMap() {
    //map创建地图实例

    map.value = new T.Map(document.getElementById("mapContainer"));

    // 设置地图中心点和缩放级别
    map.value.centerAndZoom(new T.LngLat(121.42638, 31.63153), 11);

    map.value.on("click", function (e) {
        map.value.clearOverLays();
        longitude.value = e.lnglat.lng;
        latitude.value = e.lnglat.lat;
        form.lonLat = e.lnglat.lng + "," + e.lnglat.lat;

        // getAddressInfo();
        const position = new T.LngLat(e.lnglat.lng, e.lnglat.lat);
        let icon = new T.Icon({
            iconUrl: "./icon.png", // 请求图标图片的URL
            iconSize: new T.Point(40, 40), // 图标可视区域的大小
            iconAnchor: new T.Point(30, 30) // 图标的定位锚点
        });
        const marker = new T.Marker(position, { icon: icon });
        map.value.addOverLay(marker);
    });
}

// async function getAddressInfo() {
//   let Tokens = "20f5dad7c9e6207216d4d7d971fbed3f";
//   let postStr = {
//     lon: form.lon,
//     lat: form.lat,
//     ver: 1
//   };
//   let url = "https://api.tianditu.gov.cn/geocoder";
//   // Lambda写法
//   let res = await axios({
//     method: "get",
//     url: url,
//     params: {
//       postStr: JSON.stringify(postStr),
//       type: "geocode",
//       tk: Tokens
//     },
//     timeout: 1000
//   });
//   // 响应成功回调
//   if (res.data.msg == "ok") {
//     form.cq_address_worksite = res.data.result.formatted_address;
//   }
// }
</script>

<style lang="scss">
.arco-input-wrapper .arco-input[disabled] {
    -webkit-text-fill-color: #8f7e7e !important;
}

.arco-form-item {
    margin-bottom: 10px !important;
}

.arco-input-wrapper.arco-input-disabled .arco-input-prefix,
.arco-input-wrapper.arco-input-disabled .arco-input-suffix {
    color: #000 !important;
}

.input-container {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    display: flex;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 10px;
    border-radius: 4px;
}

.coordinate-input {
    padding: 8px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: 120px;
    margin-right: 5px;
}

.locate-button {
    padding: 8px 16px;
    font-size: 14px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.locate-button:hover {
    background-color: #45a049;
}
</style>